package com.example.config.es.aspect;

import com.example.config.es.aspect.annotation.EsSync;
import com.example.config.es.template.SyncStrategy;
import com.example.util.ReflectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class EsSyncAspect {
    @Autowired
    private ApplicationContext context;
//    @Autowired
    private ReflectionUtils reflectionUtils;

    // 拦截所有带@EsSync的方法（如save、update、delete）
    @Around("@annotation(esSync) && args(entity)")
    public Object aroundSaveOrUpdate(ProceedingJoinPoint joinPoint, EsSync esSync, Object entity) throws Throwable {
        // 1. 先执行数据库操作
        Object result = joinPoint.proceed();

        // 2. 根据注解获取同步策略（强/最终）（这里是getBean通过strategy()找到@Component("")同名的Bean容器，类似抽象工厂指定接口实现类）
        SyncStrategy strategy = context.getBean(esSync.strategy(), SyncStrategy.class);

        // 3. 执行ES同步
        strategy.syncSaveOrUpdate(entity);

        return result;
    }

    // 拦截删除方法
    @Around("@annotation(esSync) && args(id)")
    public Object aroundDelete(ProceedingJoinPoint joinPoint, EsSync esSync, Object id) throws Throwable {
        // 1. 先执行数据库删除
        Object result = joinPoint.proceed();

        // 2. 执行ES同步删除
        SyncStrategy strategy = context.getBean(esSync.strategy(), SyncStrategy.class);
        strategy.syncDelete(esSync.entityClass(), id);

        return result;
    }
}
